<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
  <!-- <link rel="icon" href="/favicon.ico" /> -->

  <!-- <% if (!!htmlWebpackPlugin.options.v5options.css &&
     !!htmlWebpackPlugin.options.v5options.css.length) { %>
    <% htmlWebpackPlugin.options.v5options.css.forEach(function(item){%>
      <link href="<%= item %>" rel="stylesheet" />
      <% }) %>
        <% } %> -->
  <% if (!!htmlWebpackPlugin.options.moduleDependency.todoList.css &&
     !!htmlWebpackPlugin.options.moduleDependency.todoList.css.length) { %>
    <% htmlWebpackPlugin.options.moduleDependency.todoList.css.forEach(function(item){%>
      <link href="<%= item %>" rel="stylesheet" />
      <% }) %>
        <% } %>

</head>

<body>

  <script>
    window.customObservers = {};
    window.globalMetadata = null;
    window.globalTableData = null;
    window.addCustomObserver = function (type, callback) {
      if (customObservers[type]) {
        customObservers[type].push(callback);
      } else {
        customObservers[type] = [];
        customObservers[type].push(callback);
      }
    };
    window.dispatchCustomEvent = function (type, data) {
      if (customObservers[type]) {
        var callbacks = customObservers[type];
        for (var i = 0; i < callbacks.length; ++i) {
          callbacks[i](data);
        }
      }
    };

    // 初始化第三方扩展资源
    var _initExtendResource = function () {
        var metadataReady = false;
        var basicResourcesReady = false;

        window.addCustomObserver('getMetadata', function (data) {
            metadataReady = true;
            loadExtendResource();
        });

        window.addCustomObserver('basicResourcesLoaded', function () {
            basicResourcesReady = true;
            loadExtendResource();
        });

        let document = window.document;
        window.registerComp = (compId, schema) => {
          const customEvent = new CustomEvent(compId, {
            bubbles: true, // 允许事件冒泡
            detail: schema
          });
          document.dispatchEvent(customEvent)
        }
        function loadExtendResource() {
            // 获取到了metadata，基础JS加载完成后，才能加载三方扩展资源
            if (!metadataReady || !basicResourcesReady) {
                return;
            }
            var extendResources = window.globalMetadata
                && window.globalMetadata.extra
                && window.globalMetadata.extra.extendResources;
            console.log("加载extend资源: ", extendResources);
            if (!extendResources) {
                return;
            }
            // 加载css资源
            var pluginCssFiles = extendResources.pluginCssFiles;
            if (pluginCssFiles && pluginCssFiles.length > 0) {
                pluginCssFiles.forEach(function (path) {
                    var link = document.createElement('link');
                    link.setAttribute('rel', 'stylesheet');
                    link.setAttribute('type', 'text/css');
                    link.setAttribute('href', window._ctxPath + "/" + path + window._resSuffix);
                    document.head.appendChild(link);
                });
            }
            // 加载js资源
            var pluginJsFiles = extendResources.pluginJsFiles;
            if (pluginJsFiles && pluginJsFiles.length > 0) {
                pluginJsFiles.forEach(function (path) {
                    var script = document.createElement("script");
                    script.src = window._ctxPath + "/" + path + window._resSuffix;
                    script.async = false;
                    document.body.appendChild(script);
                });
            }
        }
    }

    var _getMetadata = function () {
      var urlParamObj = _getParams(window.location.search);
      var data = {
        key: 'LIST_PENDING', // 页面唯一标识（取值参照ListKey）
        platform: 0, // 终端 0 pc 1 mobile （取值参照PlatformType）
        arguments: {
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          userId: window._currentUser.id,
          bpmMenu: '',
          isSupervision: '',
          supervisionApproval: '',
          templateIds: urlParamObj.textfield || ''
        }
      };
      var url = window._ctxPath + '/rest/global/metadata/list';
      // window.axios.post(url, data).then(function (res) {
      //   if (res.data && res.data.code == 0) {
      //     var data = res.data.data;
      //     window.globalMetadata = data;
      //     dispatchCustomEvent('getMetadata', data);
      //   } else {
      //     window.globalMetadata = {};
      //     dispatchCustomEvent('getMetadata', {});
      //   }
      // });
      var xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var res = JSON.parse(xhr.responseText);
          if (res && res.code == 0) {
            var data = res.data;
            window.globalMetadata = data;
            dispatchCustomEvent('getMetadata', data);
          } else {
            window.globalMetadata = {};
            dispatchCustomEvent('getMetadata', {});
          }
        }
      };
      xhr.send(JSON.stringify(data));
    };

    var _getTableData = function () {
      var urlParamObj = _getParams(window.location.search);
      var searchConditions = {};
      searchConditions.aiSort = 'false';
      searchConditions.templeteIds = urlParamObj.textfield || '';
      var sendParams = [
        { page: 1 },
        searchConditions
      ];
      var args = 'managerMethod=getPendingList&arguments=' + JSON.stringify(sendParams);
      var url = window._ctxPath + '/ajax.do?method=ajaxAction&managerName=colManager&rnd=33539';
      // window.axios
      //   .post(url, args, {
      //     headers: {
      //       'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      //     }
      //   })
      //   .then(function (data, err) {
      //     const result = data.data;
      //     if (result) {
      //       window.globalTableData = result;
      //       dispatchCustomEvent('getTableData', window.globalTableData);
      //     } else {
      //       window.globalTableData = {};
      //       dispatchCustomEvent('getTableData', window.globalTableData);
      //     }
      //   })
      //   .catch(function (error) {
      //     window.globalTableData = {};
      //     dispatchCustomEvent('getTableData', window.globalTableData);
      //   });
      var xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var res = JSON.parse(xhr.responseText);
          if (res) {
            window.globalTableData = res;
            dispatchCustomEvent('getTableData', window.globalTableData);
          } else {
            window.globalTableData = {};
            dispatchCustomEvent('getTableData', window.globalTableData);
          }
        }
      };
      xhr.send(args);
    };

    var _getParams = function (locationSearch) {
      var result = {};
      var searchStr = locationSearch || window.location.search;
      var paramster = searchStr.split('?');

      if (paramster.length > 1) {
        var hrefStr = paramster[1];
        var paramArr = hrefStr.split('&');
        for (var i = 0; i < paramArr.length; i++)
          result[paramArr[i].split('=')[0]] = paramArr[i].split('=')[1];
      }

      return result;
    };

    _initExtendResource();
    _getMetadata();
    _getTableData();
    function loadResource(cssArr, jsArr) {
      cssArr.forEach(function (v) {
        var cssFile = document.createElement('link');
        cssFile.rel = 'stylesheet';
        cssFile.href = v;
        document.getElementsByTagName('head')[0].appendChild(cssFile);
      });

      jsArr.forEach(function (v) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = false;
        script.defer = false;
        script.src = v;
        document.getElementsByTagName('head')[0].appendChild(script);
      });
    }
    window.addEventListener('load', function () {
      var cssArr = [
        window._staticPath + '/common/all-min.css' + window._staticSuffix,
        window._staticPath + '/skin/dist/min/skinComponents-defaultTheme-min.css' + window._staticSuffix,
      ];
      var jsArr = [
        window._staticPath + '/common/coll-min.js' + window._staticSuffix,
        window._staticPath + '/apps_res/collaboration/js/batch.js' + window._staticSuffix,
        window._staticPath + '/common/colList-min.js' + window._staticSuffix,
        window._staticPath + '/common/workflow/workflowDesigner_ajax.js' + window._staticSuffix,
        window._staticPath + '/common/workflow/workflowDesigner_api-min.js' + window._staticSuffix,
        window._staticPath + '/apps_res/collaboration/js/CollaborationApi.js' + window._staticSuffix,
        window._staticPath + '/common/cap-dynamic-front/load.js' + window._staticSuffix
      ];

      loadResource(cssArr, jsArr);
      dispatchCustomEvent('basicResourcesLoaded');
    })
  </script>

  <!-- <% if (!!htmlWebpackPlugin.options.v5options.js &&
     !!htmlWebpackPlugin.options.v5options.js.length) { %>
    <% htmlWebpackPlugin.options.v5options.js.forEach(function(item){%>
      <script src="<%= item %>" type="text/javascript"></script>
      <% }) %>
        <% } %> -->
  <% if (!!htmlWebpackPlugin.options.moduleDependency.todoList.js &&
     !!htmlWebpackPlugin.options.moduleDependency.todoList.js.length) { %>
    <% htmlWebpackPlugin.options.moduleDependency.todoList.js.forEach(function(item){%>
      <script src="<%= item %>" type="text/javascript"></script>
      <% }) %>
        <% } %>

          <!-- 自定义html模版 -->
          <div id="app"></div>
</body>

</html>
